import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux, Redirect } from 'dva/router';
import { Avatar, Icon, Form, Input, Button, Select, Row, Col, Popover, Progress, Alert, message } from 'antd';
import styles from './Login.less';
import RegisterStyle from './Register.less';
import { ORIGIN } from '../../constants';
import querystring from 'querystring';
import { queryUserBySms, UserLogin } from '../../services/user';
import TrimSpan from '../../components/TrimSpan';

const FormItem = Form.Item;
const { Option } = Select;
const InputGroup = Input.Group;

@connect(state => ({
  register: state.register,
}))
@Form.create()

export default class Login extends Component {
  state = {
    count: 0,
    confirmDirty: false,
    loginType: 'taobao', // taobao phone choose
    help: '',
    users: [],
    sms_code: '',
    avatars: [
      'http://oyufgm5i2.bkt.clouddn.com/avator_1.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_2.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_3.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_4.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_5.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_6.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_7.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_8.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_9.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_10.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_11.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_12.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_13.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_14.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_15.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_16.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_17.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_18.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_19.png',
      'http://oyufgm5i2.bkt.clouddn.com/avator_20.png',
    ],
  }

  componentWillReceiveProps(nextPorps) {
  }
  componentWillMount() {
    const query = querystring.parse(this.props.location.search.substr(1));
    if (query.loginType === 'choose') {
      this.props.dispatch({
        type: 'user/fetchCurrent',
        callback: (result) => {
          if (!result.error) {
            this.setState({
              loginType: query.loginType,
              users: result.users,
            });
          }
        },
      });
    }
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  onGetCaptcha = () => {
    this.props.form.validateFields(['phone'], (err, values) => {
      if (!err) {
        this.props.dispatch({
          type: `login/getSmsCode`,
          payload: {
            phone: this.props.form.getFieldValue('phone')
          },
        });
        let count = 59;
        this.setState({ count });
        this.interval = setInterval(() => {
          count -= 1;
          this.setState({ count });
          if (count === 0) {
            clearInterval(this.interval);
          }
        }, 1000);
      }
    });
  }

  handleRegister = () => {
    this.props.dispatch(routerRedux.push('/user/register'));
  }

  handleSubmit = (e) => {
    this.props.form.validateFields({ force: true },
      async (err, values) => {
        if (!err) {
          const result = await UserLogin(values);
          console.log(result)
          if (result.error) {
            message.error(result.msg)
          } else {
            location.href = '/index.html';
          }
        }
      }
    );
  }

  handlesmsSubmit = (e) => {
    this.props.form.validateFields({ force: true },
      async (err, values) => {
        if (!err) {
          this.setState({ sms_code: values.sms_code });
          const result = await queryUserBySms(values);
          if (result.error) {
            message.error(result.msg)
          } else {
            if (result.users && result.users.length > 1) {
              console.log(result.users)
              this.setState({
                loginType: 'choose',
                users: result.users,
                sms_code: values.sms_code
              });
            } else if (result.users && result.users[0]) {
              const user = result.users[0];
              this.hanldLogin(user._id)
            } else {
              message.error('用户不存在');
            }
          }
        }
      }
    );
  }

  renderMessage = (message) => {
    return (
      <Alert
        style={{ marginBottom: 24 }}
        message={message}
        type="error"
        showIcon
      />
    );
  }

  hanldLogin = (user_id, phone, sms_code) => {
    this.props.dispatch({
      type: `login/submit`,
      payload: {
        user_id,
      },
      callback: (result) => {
        location.href = '/index.html';
      }
    })
  }

  render() {
    const { form, register } = this.props;
    const { getFieldDecorator } = form;
    const { count, users } = this.state;
    const state = {
      // redirect_uri: `${location.origin}/index.html#/user/register`,
      redirect_uri: `${location.origin}/index.html`,
      web_origin: location.origin,
    };
    return (
      <div>
        {this.state.loginType === 'phone' &&
          <div className={RegisterStyle.main} style={{ height: 300, position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, margin: 'auto', }}>
            <h3>账号登录</h3>
            <Form>
              {
                register.error &&
                this.renderMessage(register.msg)
              }
              <FormItem>
                {getFieldDecorator('phone', {
                  rules: [{
                    required: true, message: '请输入手机号！',
                  }, {
                    pattern: /^1\d{10}$/, message: '手机号格式错误！',
                  }],
                })(
                  <Input size="large" placeholder="11位手机号" />
                )}
              </FormItem>
              <FormItem>
                    {getFieldDecorator('password', {
                      rules: [{
                        required: true, message: '请输入密码',
                      }],
                    })(
                      <Input
                        size="large"
                        type="password"
                        placeholder="输入密码"
                      />
                    )}
              </FormItem>

              <FormItem style={{ marginTop: 25, width: 320 }}>
                <Button onClick={this.handleSubmit} size="large" loading={register.submitting} className={RegisterStyle.submit} type="primary" htmlType="submit">
                  登录
              </Button>
              </FormItem>
              <a onClick={() => this.setState({ loginType: 'taobao' })}>返回淘宝登录</a>
            </Form>
          </div>}
        {this.state.loginType === 'taobao' &&
          <div className={styles.main}>
            <div>
              <div style={{ marginBottom: 20 }} className={styles.desc}>使用淘宝授权登录</div>
              <a href={`https://oauth.taobao.com/authorize?client_id=23670142&response_type=code&redirect_uri=${ORIGIN}/api/taobao/auth&state=${encodeURIComponent(querystring.stringify(state))}&view=web`}>
                <Icon type="taobao-circle" className={styles.iconTaobao} />
              </a>
            </div>
            <div style={{ height: 30 }}></div>
            <a style={{ position: 'relative', right: 120, top: 50 }} onClick={this.handleRegister} >免费注册</a>
            <a style={{ position: 'relative', top: 50 }} onClick={() => this.setState({ loginType: 'smslogin' })} >验证码登录</a>
            <a style={{ position: 'relative', left: 120, top: 50 }} onClick={() => this.setState({ loginType: 'phone' })} >账号登录</a>
          </div>
        }{
          this.state.loginType === 'smslogin' &&
          <div className={RegisterStyle.main} style={{ height: 300, position: 'absolute',left:0, right:0, top:0, bottom:0, margin:'auto',  }}>
            <h3>短信验证码登录</h3>
            <Form>
              {
                register.error &&
                this.renderMessage(register.msg)
              }
              <FormItem>
                {getFieldDecorator('phone', {
                  rules: [{
                    required: true, message: '请输入手机号！',
                  }, {
                    pattern: /^1\d{10}$/, message: '手机号格式错误！',
                  }],
                })(
                  <Input size="large" placeholder="11位手机号" />
                )}
              </FormItem>
              <FormItem>
                <Row gutter={8}>
                  <Col span={16}>
                    {getFieldDecorator('sms_code', {
                      rules: [{
                        required: true, message: '请输入验证码！',
                      }],
                    })(
                      <Input
                        size="large"
                        placeholder="验证码"
                      />
                    )}
                  </Col>
                  <Col span={8}>
                    <Button
                      size="large"
                      style={{ width: 100 }}
                      disabled={count}
                      className={styles.getCaptcha}
                      onClick={this.onGetCaptcha}
                    >
                      {count ? `${count} s` : '获取验证码'}
                    </Button>
                  </Col>
                </Row>
              </FormItem>

              <FormItem style={{ marginTop: 25, width: 320 }}>
                <Button onClick={this.handlesmsSubmit} size="large" loading={register.submitting} className={RegisterStyle.submit} type="primary" htmlType="submit">
                  登录
              </Button>
              </FormItem>
              <a onClick={() => this.setState({ loginType: 'taobao' })}>返回淘宝登录</a>
            </Form>
          </div>
        }
        {this.state.loginType === 'choose' &&
          <div className={styles.main} style={{ maxHeight: 350, overflow: 'auto' }}>
            {users.map(item => {
              return (
                <a style={{ display: 'inline-block', marginRight: 40 }} key={item._id} onClick={() => this.hanldLogin(item._id, item.phone, this.state.sms_code)}>
                  <Avatar src={item.avatar} size="large" />
                  <p key={item.nickname}><TrimSpan text={item.nickname} length={4} /></p>
                </a>
              )
            })}
          </div>
        }
      </div>
    );
  }
}